import { useUserInfoApi } from "@/api";
import { Message } from "@arco-design/web-vue";
import { defineStore } from "pinia";
import LocalCache from "@/utils/storage";
import router from "@/router/index";

interface userInfoType {
  userId: string;
  userName: string;
  nickName: string;
  role: number;
  avater: string;
  token: string;
}
interface userStoreType {
  userInfo: userInfoType;
}
const roleName = ["-", "超级管理员", "普通用户"];

export const userStorer = defineStore("userStore", {
  state: (): userStoreType => {
    return {
      userInfo: {
        userId: "",
        userName: "",
        nickName: "",
        role: 2,
        avater: "",
        token: "",
      },
    };
  },

  actions: {
    async saveUserInfo(token: string) {
      this.userInfo.token = token;
      // const { data } = await useUserInfoApi({ token });
      const { data } = await useUserInfoApi();
      this.userInfo = data;
      console.log(this.userInfo.role, "111");

      LocalCache.set("userInfo", JSON.stringify(this.userInfo));
    },

    loadUserInfo() {
      const userInfo = LocalCache.get("userInfo");
      if (!userInfo) {
        return;
      }
      try {
        this.userInfo = JSON.parse(userInfo);
      } catch (error) {
        Message.error("用户信息获取失败");
        return;
      }

      const nowTime = new Date().getTime();
      console.log(Number(this.userInfo.token), nowTime);

      if (Number(this.userInfo.token) - nowTime <= 0) {
        Message.warning("登录过期，请重新登录");
        console.log("guoqi");

        LocalCache.clear();
        router.push({
          name: "Login",
        });
        return;
      }
    },
    logout() {
      LocalCache.clear();
      this.userInfo = {
        userId: "",
        userName: "",
        nickName: "",
        role: 2,
        avater: "",
        token: "",
      };
      Message.success('退出成功')
      router.push({
        name: "Login",
      });
    },
  },

  getters: {
    isLogin(): boolean {
      return this.userInfo.token !== "";
    },
    isAdmin(): boolean {
      return this.userInfo.role === 1;
    },
  },
});
